<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Address;
use app\common\model\Category;
use app\common\model\Order;
use app\common\model\Goods as goodsModel;
use app\common\model\GoodsAttr;
use app\common\model\GoodsComment;
use app\common\model\User;
use think\Db;

/**
 * 商品接口
 */
class Goods extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 商品详情
     * @param string $token token
     * @param string $goods_id 商品ID
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618801196",
    "data": {
    "id": 1,商品ID
    "name": "香辣酱",商品名称
    "images": [图片
    "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",
    "http://www.shop.com/uploads/20210406/abc4e70e2ae6e7bc73934a05fb4fee9a.png"
    ],
    "video_image": "",商品视频
    "content": "<p><b>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情这是一个商品详情</b><br></p>",商品详情
    "sales": 0,销量
    "price": "25.00",价格
    "goods_attr": [商品规格
    {
    "id": 13,规格ID
    "goods_id": 1,
    "attr_name": "50g",规格名称
    "price": "25.00",规格价格
    "stock": 1000,库存
    "createtime": 1617714506
    }
    ],
    "status_text": ""
    }
    })
     */
    public function goods_detail()
    {
        $token = $this->request->get('token');
        if($token){
            $user_info = User::where('token', $token)->field('id')->find();
        }else{
            $user_info = null;
        }
        $goods_id = $this->request->get('goods_id');
        $goods_info = goodsModel::where(['id' => $goods_id, 'status' => 0])->field('id,name,images,video_image,content,sales,price')->find();
        if ($goods_info) {
            $images = explode(',', $goods_info['images']);
            foreach($images as &$v1){
                $v1 = $this->domain.$v1;
            }
            $goods_info['images'] = $images;
            if($goods_info['video_image']){
                $goods_info['video_image'] = $this->domain.$goods_info['video_image'];
            }
            $goods_info['content'] = get_img_thumb_url($goods_info['content'],$this->domain);
            //商品规格
            $goods_info['goods_attr'] = GoodsAttr::where('goods_id', $goods_info['id'])->order('id asc')->select();
            $this->success($goods_info);
        } else {
            $this->error('数据异常');
        }
    }
    /**
     * 确认订单页面
     * @param string $token 用户token
     * @param string $goods_id 商品ID
     * @param string $attr_id 商品规格ID
     * @param string $num 商品数量
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618801443",
    "data": {
    "goods_info": [
    {
    "id": 1,商品ID
    "name": "香辣酱",商品名称
    "images": "http://www.shop.com/uploads/20210406/998bcbc925dd59eb924d7a100b9c0d1f.png",商品图片
    "attr_id": 13,规格ID
    "attr_name": "50g",规格名称
    "price": "25.00",单价
    "num": "2",数量
    "status_text": ""
    }
    ],
    "total_price": 50,总价
    "address": null，收货地址
    }
    })
     */
    public function confirm_order()
    {
        $token = $this->request->get('token');
        $user_info = User::where('token', $token)->field('id')->find();
        $goods_id = $this->request->get('goods_id');
        $attr_id = $this->request->get('attr_id');
        $num = $this->request->get('num')==null?1:$this->request->get('num');
        $goods_info = goodsModel::where(['id' => $goods_id, 'status' => 0])->field('id,name,images')->find();
        if ($goods_info) {
            $images = explode(',', $goods_info['images']);
            $goods_info['images'] = $this->domain.$images[0];
            $attr_info = GoodsAttr::where('goods_id', $goods_info['id'])->where('id', $attr_id)->find();
            if ($attr_info) {
                $goods_info['attr_id'] = $attr_info['id'];
                $goods_info['attr_name'] = $attr_info['attr_name'];
                $goods_info['price'] = $attr_info['price'];
                if (intval($num) > $attr_info['stock']) {
                    $this->error('购买数量大于库存');
                }
                //商品价格
                $price = $goods_info['price']*$num;
                $goods_info['num'] = $num;
                //收货地址
                $address = Address::where(['userid' => $user_info['id'], 'is_default' => 1])->find();
                if($address){
                    $address['address'] = $address['province'].$address['city'].$address['area'].$address['address'];
                }
                $list[0] = $goods_info;
                $total_price =$price;
                $data = [
                    'goods_info' => $list,
                    'total_price' => $total_price,
                    'address' => $address,
                ];
                $this->success($data);
            }
        }
        $this->error('数据异常');
    }
    /**
     * 商品立即购买
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $goods_id 商品ID
     * @param string $attr_id 商品规格ID
     * @param string $num 商品数量
     * @param string $coupon_id 优惠券ID,没有为null
     * @param string $address_id 收货地址ID
     * @param string $type 支付方式1支付宝2微信
     * @param string $note 备注
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1596684503",
    "data": [
    0.06,
    0.01
    ]
    })
     */
    public function buy_now()
    {
        $token = $this->request->post('token');
        $user_info = User::where('token', $token)->field('id')->find();
        $goods_id = $this->request->post('goods_id');
        $attr_id = $this->request->post('attr_id');
        $num = $this->request->post('num');
        $coupon_id = $this->request->post('coupon_id');
        $address_id = $this->request->post('address_id');
        $note = $this->request->post('note');
        $type = $this->request->post('type');
        $goods_info = goodsModel::where(['id' => $goods_id, 'status' => 0])->field('id,name,images')->find();
        if ($goods_info) {
            $images = explode(',', $goods_info['images']);
            $goods_info['images'] = $images[0];
            $attr_info = GoodsAttr::where('goods_id', $goods_info['id'])->where('id', $attr_id)->find();
            if ($attr_info) {
                if (intval($num) > $attr_info['stock']) {
                    $this->error('购买数量大于库存');
                }
                //商品总价
                $total_price = $attr_info['price'] * $num;

                $coupon_money = 0;
                //实际支付金额
                $actual_price = $total_price - $coupon_money;
                //收货地址
                if($address_id){
                    $address_info  = Address::where(['userid'=>$user_info['id'],'id'=>$address_id])->find();
                    if(empty($address_info)){
                        $this->error('收货地址不存在');
                    }
                }
                if($actual_price <0.01){
                    $this->error('金额错误');
                }
                //创建订单
                $data = [
                    'userid'=>$user_info['id'],
                    'price'=>$total_price,
                    'discounted_price'=>$coupon_money,
                    'actual_price'=>$actual_price,
                    'username'=>$address_info['username'],
                    'mobile'=>$address_info['mobile'],
                    'address'=>$address_info['province'].$address_info['city'].$address_info['area'].$address_info['address'],
                    'is_coupon'=>$coupon_id,
                    'note'=>$note,
                    'paytype'=>$type,
                    'createtime'=>time(),
                ];
                $data['order_sn'] = getOrderSn();
                Db::startTrans();
                try {
                    $res = Order::insertGetId($data);
                    if($res){
                        $order_goods = [
                            'order_id'=>$res,
                            'goods_id'=>$goods_info['id'],
                            'attr_id'=>$attr_info['id'],
                            'goods_name'=>$goods_info['name'],
                            'goods_image'=>$goods_info['images'],
                            'attr_name'=>$attr_info['attr_name'],
                            'unit_price'=>$attr_info['price'],
                            'num'=>$num,
                            'createtime'=>time(),
                        ];
                        $res1 = Db::name('order_goods')->insert($order_goods);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if($res && $res1){
                    if($type == 1){
                        //支付宝支付
                        $title = '订单信息'.$data['order_sn'];
                        $amount = abs($data['actual_price']);
                        $notify_url =  $this->request->root(true) . '/api/pays/goods_response/type/alipay';

                        $result = \addons\epay\library\Service::submitOrder($amount,$data['order_sn'],'alipay',$title,$notify_url,'','app');

                        //$result = ali_pay($title,$notify_url,$amount,$data['zong_order_sn']);
                        $this->success($result);
                    }elseif($type ==2){
                        //微信支付
                        $title = '订单信息'.$data['order_sn'];
                        $amount = abs($data['actual_price']);
                        $notify_url =  $this->request->root(true) . '/api/pays/goods_response/type/wechat';
                        $result = \addons\epay\library\Service::submitOrder($amount,$data['order_sn'],'wechat',$title,$notify_url,'','app');
                        //$result = wechat_pay($title,$notify_url,$amount,$data['zong_order_sn']);
                        $this->success($result);
                    }
                }
            }
        }
        $this->error('数据异常');
    }
}